<?php
declare (strict_types=1);

namespace app\school\logic\school;

use app\admin\logic\user\Account as AdminUser;
use app\common\exception\LogicException;
use app\common\logic\advert\AdvertLink;
use app\common\logic\category\Category;
use app\course\logic\base\Course;
use app\course\logic\base\CourseStudent;
use app\school\event\subscribes\school\School as SchoolSubscribe;
use app\school\logic\school\admin\SchoolDomain;
use app\school\model\school\School as SchoolModel;
use app\topic\logic\Topic;
use app\user\logic\teacher\Teacher;
use ArrayObject;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Event;
use think\facade\Request;
use think\helper\Str;

/**
 * 后台管理逻辑层
 */
class School extends SchoolModel
{
    /**
     * 机构列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-12
     */
    public function getList(array $map = [])
    {
        $field = 'id,title,logo,intro,update_time,best_sort';

        return $this->with(['logo_url'])->status()->where($map)->field($field)->order(['best_sort' => 'asc', 'update_time' => 'desc'])
            // ->order('update_time', 'DESC')
            ->paginate(static::getListRows())->each(function ($i) {
                $i->sdn = app(SchoolDomain::class)->getEffectivePcDomain($i->id);//'http://m' . $i->id . '.' . Tool::pregDomain(config('eduline.appinfo.pc_host'));
            });
    }

    /**
     * 获取机构独立域名
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/03/10
     *
     * @param $id
     * @return mixed|string
     */
    public function getSdn($id)
    {
        $host = config('eduline.appinfo.pc_host');
        if ($id == 1) return $host;

        return app(SchoolDomain::class)->getEffectivePcDomain(intval($id));// 'http://m' . $id . '.' . Tool::pregDomain($host);
    }

    /**
     * 机构select表单，下拉选择机构
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-06-07
     */
    public function getSelectList()
    {
        $field = 'id,title';

        return $this->public()->status()->field($field)->order('update_time', 'DESC')->select();
    }

    // 根据机构title搜索机构

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function search($title, $detail = false)
    {
        // 验证数据
        if ($title) {
            $field = $detail ? '*' : 'id,title';

            return $this->where('title', 'LIKE', '%' . $title . '%')->field($field)->select();
        }

        return new ArrayObject();
    }

    // 机构主页

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getHomePage($id): array
    {
        $data        = [];
        $device_type = request()->device_type;
        if ($device_type == 'pc') {
            $limit          = 8;
            $data['banner'] = app(AdvertLink::class)->getLinkUrlByKey('"pc.school.index"');
        } else {
            $limit = 6;
        }

        // 基础信息
        $info = $this->field('id,title,logo,intro')->with(['logo_url'])->findOrEmpty($id);

        if (!request()->is_pc) $info->info = Request::domain() . '/school/' . $id . '/info';
        $data['info'] = $info;

        // 推荐课程
        $data['course'] = app(Course::class)->where('mhm_id', $id)->whereNull('delete_time')->scope('status,listingTime,solo,expire')->field('id,course_type,title,price,vip_price,cover,sale_count,sale_count_market')->with('cover_url')->order('best_sort', 'ASC')->limit($limit)->select()->append(['course_type_text', 'user_price']);

        // 推荐讲师
        $data['teacher'] = app(Teacher::class)->where('mhm_id', $id)->scope(['status', 'undelete'])->with(['avatar'])->field('id,level_id,user_id')->order('best_sort', 'ASC')->limit(4)->select()->append(['teacher_name', 'level_text'])->each(function ($i) {
            // $i->level_text = $i->level_text ? : '普通讲师';
            $i->avatar_url = $i->avatar ? $i->avatar->fileurl : '';
        })->hidden(['avatar']);

        // 推荐资讯
        $data['topic'] = app(Topic::class)->getSchoolRecommendTopics($id);

        return $data;
    }

    public function getInfo($id)
    {
        return $this->field('id,title,logo,info')->findOrEmpty($id);
    }

    public function getInfoTxt($id)
    {
        return $this->where('id', $id)->value('info');
    }

    // 机构课程 - 加载课程或筛选课程

    /**
     * @throws DbException
     */
    public function getCourse(array $map = [])
    {
        return app(Course::class)->where($map)->field('id,course_type,title,price,vip_price,cover,sale_count,sale_count_market')->scope('status,listingTime,solo,expire')
            ->with('cover_url')->order(['best_sort' => 'ASC', 'id'])
            // ->limit(input('get.page/d') * input('get.count/d'), input('get.count/d'))
            // ->buildSql();
            ->paginate(static::getListRows())->append(['user_price', 'course_type_text'])->each(function ($i) {
                $i->is_buy = app(CourseStudent::class)->isBuy($i->id);
            });
    }

    /**
     * 机构认证页面渲染
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-06-08
     */
    public function authFetch(): array
    {
        $mid         = static::$mid;
        $status_text = $this::getStatusText();
        // 检查认证状态
        $auth_info = $this
            ->where('user_id', $mid)
            ->with(['legal_IDcard_positive_url', 'legal_IDcard_side_url', 'business_license_url', 'logo_url'])
            ->findOrEmpty();
        if ($auth_info->isEmpty()) {
            $return['auth_status']      = 4; //未认证
            $return['auth_status_text'] = '未认证';
            $return['auth_info']        = new ArrayObject();
        } else if ($auth_info->delete_time) {
            $return['auth_status']      = 5;
            $return['auth_status_text'] = '已注销';
            $return['auth_info']        = $auth_info;
        } else {
            $return['auth_status']        = $auth_info->status;
            $return['auth_status_text']   = $status_text[$auth_info->status];
            $auth_info->selected_category = app(Category::class)->getCateLastText($auth_info->fullcategorypath);
            $return['auth_info']          = $auth_info;
        }
        // pc端数据 - 机构分类
        // if (in_array(request()->device_type, ['pc', 'h5', 'miniprogram'])) {
        $return['category'] = app(Category::class)->getTree(0, 'id,title,sort', 2);

        // }

        return $return;
    }

    /**
     * 机构认证提交信息
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-06-08
     */
    public function authSubmit($param)
    {
        // 验证数据
        $this->getValidate()->scene('auth')->failException()->check($param);

        $param = app(Category::class)->parseFullCateParam($param);

        // 检查法人身份证重复
        // 用户只能认证一个机构
        $mid   = static::$mid;
        $exist = $this->where('user_id', $mid)->findOrEmpty();

        if ($exist->isEmpty()) {
            // 用户手机号已注册后台账号
            $phone = request()->user->phone;
            $exist = app(AdminUser::class)->where('phone', $phone)->findOrEmpty();

            if (!$exist->isEmpty()) throw new LogicException('您已认证过机构管理员，请先注销后台账号');
            // 账号已认证
            $exist = $this->where('legal_IDcard', $param['legal_IDcard'])->findOrEmpty();

            if (!$exist->isEmpty()) throw new LogicException('此身份证已认证过机构');
            // 提交认证
            // 分类确认
            $param['user_id']     = $mid;
            $param['from']        = request()->device_type;
            $param['school_code'] = 'JG' . Str::random(15, 2, '1234567890');
            $param['school_type'] = 1;
            $param['info']        = '';
            $param['status']      = 2;

            // return $param;
            $success = $this::create($param);
            if ($success->isEmpty()) throw new LogicException('提交认证失败');
            // 审核日志
            app(SchoolLog::class)->writeLog(intval($success->id), '提交审核', $mid);
            // 机构提交了审核
            Event::subscribe(SchoolSubscribe::class);
            Event::trigger('SchoolAuthSubmit', $success);

            return $success;
        } else {

            // 检查状态     0:禁用 1:正常  2:待认证 3:认证被驳回
            if (in_array($exist->status, [0, 1, 2])) throw new LogicException('你已认证过机构，请勿重复认证');
            // 身份证已被其他账号认证
            $used = $this->where('legal_IDcard', $param['legal_IDcard'])->where('user_id', '<>', $mid)->findOrEmpty();

            if (!$used->isEmpty()) throw new LogicException('此身份证已认证过其他机构，请核实身份信息');

            $param['from']   = request()->device_type;
            $param['status'] = 2;

            $success = $exist->save($param);

            if (!$success) throw new LogicException('提交认证失败');
            // 重新提交机构认证
            Event::subscribe(SchoolSubscribe::class);
            Event::trigger('SchoolAuthSubmit', $exist);
            // 审核日志
            app(SchoolLog::class)->writeLog(intval($exist->id), '重新提交审核', $mid);

            return $exist;
        }
    }

    // 首页推荐机构
    public function getRecommend()
    {
        return $this->status()->recommend()->field('id,title,logo')->limit(5)->select();
    }

    // 获取机构信息
    public function getSchoolInfo($mhm_id)
    {
        $data = $this
            ->field('id,title,logo')
            ->withCount(['course'])
            ->findOrEmpty($mhm_id)
            ->append(['logo_url']);

        return $data->isEmpty() ? new ArrayObject() : $data;
    }

    // 获取机构所属人
    public function getSchoolUserId($id)
    {
        return $this->where('id', $id)->value('user_id') ?: 0;
    }

    // 获取机构所属人
    public function getSchoolAdminUserId($id)
    {
        return $this->where('id', $id)->value('admin_user_id') ?: 0;
    }

    // 获取机构title
    public function getSchoolTitle($id)
    {
        return $this->where('id', $id)->value('title') ?: '';
    }

    // 获取机构等级
    public function getSchoolLevelInfo($id = 0)
    {
        return $this->with(['level_info'])->where('id', $id)->findOrEmpty();
    }
}
